mksharesim_FE <- function(betatrue, theta2_true, betaf_true, x_char, v, xi, prods, T, sharesum, marketForProducts, K, K_A, nD, marketStarts, marketEnds, nn, sigmaf_true, countries) {
  
delta = x_char%*%rbind(betatrue, betaf_true) + xi  
  
MU = matrix(0,nrow(x_char),nn)

for (dd in 1:nD) {
for (t in 1:T) {
MU[marketStarts[t]:marketEnds[t],] = MU[marketStarts[t]:marketEnds[t],] + (x_char[marketStarts[t]:marketEnds[t],] %*% (diag(as.numeric(rbind(as.matrix(theta2_true[,dd]), as.matrix(betaf_true)*sigmaf_true[dd,1]))) %*% v[((dd-1)*(K+1)+1):(dd*(K+1)),,t])) 
}
}

numer <- exp(matrix(rep(delta,nn), nrow(delta), nn) + MU)   #exp of utility for each simulated consumer

sum1<-sharesum%*%numer
sum11<-1/(1+sum1)	                      # this is the denominator of the shares
sum11<-as.matrix(sum11)
denom1<-sum11[marketForProducts,]       # this expands the denominator
shareForDraws <- numer*denom1           # simulated shares for each draw
share <- rowMeans(shareForDraws) 		
share<-as.matrix(share)
nopurch <- as.matrix(rowMeans(sum11))
share_nopurch <- rbind(share, nopurch)

return(share_nopurch)  

}